/*
 * @Author: mylesshie@gmail.com
 * @Date: 2020-07-14 15:19:14
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-08-15 21:54:11
 * @description:
 */

import React, { useCallback, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { FlatList, SafeAreaView } from 'react-native'
import EmptyList from '@/components/EmptyList'
import MessageItem from '@/components/MessageItem'
import styles from './styles'
import * as userActions from '@/actions/user'

const Messages = props => {
  const dispatch = useDispatch()
  const [commentList, setCommentList] = useState([])
  const [pageNum, setPageNum] = useState(1)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [pageEnd, setPageEnd] = useState(false)
  const pageSize = 20

  const getList = useCallback(() => {
    dispatch(userActions.getMessages(pageNum, pageSize)).then(res => {
      setIsRefreshing(false)
      if (pageNum === 1) {
        setCommentList(res.list)
      } else {
        setCommentList(commentList.concat(res.list))
      }
      setPageEnd(res.total <= res.pageNum * res.pageSize)
    })
  }, [dispatch])

  useEffect(() => {
    getList()
  }, [pageNum, pageSize])

  const _renderItem = ({ item }) => (
    <MessageItem
      articleId={item.articleId}
      articleTitle={item.articleTitle}
      title={item.pushTitle}
      msg={item.pushMsg}
      date={item.createdTime}
    />
  )

  const _onRefresh = () => {
    setPageNum(1)
    setIsRefreshing(true)
    getList()
  }

  const _onLoadMore = () => {
    if (pageEnd) return
    setPageEnd(pageNum + 1)
    getList()
  }

  return (
    <>
      <SafeAreaView style={styles.wrap}>
        <FlatList
          data={commentList}
          renderItem={_renderItem}
          onRefresh={_onRefresh}
          refreshing={isRefreshing}
          onEndReached={_onLoadMore}
          keyExtractor={item => item.createdTime}
          ListEmptyComponent={<EmptyList />}
        />
      </SafeAreaView>
    </>
  )
}

export default Messages
